package cn.wolfcode.mq;

import cn.wolfcode.ws.WebSocketEP;
import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * Created by wolfcode-lanxw
 */
@Component
@RocketMQMessageListener(consumerGroup = "OrderResultGroup",topic = MQConstants.ORDER_RESULT_TOPIC)
public class OrderResultListener implements RocketMQListener<OrderMQResult> {
    @Override
    public void onMessage(OrderMQResult message) {
        System.out.println("进行消息的通知:"+ JSON.toJSONString(message));
        int count = 0;
        while(count<3){
            Session session = WebSocketEP.clients.get(message.getToken());
            if(session!=null){
                try {
                    session.getBasicRemote().sendText(JSON.toJSONString(message));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return;
            }
            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            count++;
        }
        System.out.println("没有获取到关系，无法通知");
    }
}
